package com.fengwk.support.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * WebSocket控制器
 */
public class WebSocketHandler extends TextWebSocketHandler {

	protected final static Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);

	/**
	 * WebSocket的session缓存
	 */
	@Autowired
	protected WebSocketSessionManager webSocketSessionManager;
	
	public WebSocketHandler() {
		// nothing to do
	}

	/**
	 * 连接建立后
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		logger.debug("connect to the websocket success...");
		webSocketSessionManager.afterSessionCreate(session);
	}

	/**
	 * 处理信息,调用接口的方法类
	 */
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		webSocketSessionManager.handler(session, message);
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		logger.debug("handle transport error...");
		WebSocketUtils.closeSession(session);
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		logger.debug("websocket connection closed...");
		webSocketSessionManager.afterSessionDestroy(session);
	}

	@Override
	public boolean supportsPartialMessages() {
		return super.supportsPartialMessages();
	}

}